package com.xiyou.rmls.guiderule;

import java.util.*;
import java.lang.*;

function Boolean isInSet(Object objSet, String key) {
    if (!Objects.isNull(objSet)) {
        HashSet<String> hashSet = (HashSet<String>) objSet;
        if (hashSet.contains(key)) {
            return true;
        }
    }
    return false;
}

function Boolean judgeSetSize(Object objSet, int beginSize, int endSize) {
    if (!Objects.isNull(objSet)) {
        HashSet<String> hashSet = (HashSet<String>) objSet;
        int size = hashSet.size();
        if (size > beginSize && size <= endSize) {
            return true;
        }
    }
    return false;
}

function Boolean isInList(Object objList, String key) {
    if (!Objects.isNull(objList)) {
        ArrayList<String> list = (ArrayList<String>) objList;
        if (list.contains(key)) {
            return true;
        }
    }
    return false;
}

<#list templateDrlInfo.drlInfoDtoList! as guideRuleInfo>
rule "${guideRuleInfo.ruleName}"
<#list guideRuleInfo.attributeList! as attribute>
${attribute}
</#list>
    when
        $insertMap: Map(
            this["${templateDrlInfo.preRuleName}_trigger_flag"] == null,
            eval(isInList(this["${templateDrlInfo.preRuleName}_trigger_info"], "${guideRuleInfo.ruleName}")) == false<#if guideRuleInfo.whenStack?? && guideRuleInfo.whenStack?size != 0>,</#if>
            <#if guideRuleInfo.whenStack?? && guideRuleInfo.whenStack?size != 0>
                <#list 0..(guideRuleInfo.whenStack!?size-1) as i>
            ${guideRuleInfo.whenStack[i]}<#if i != guideRuleInfo.whenStack!?size-1>,</#if>
                </#list>
            </#if>
        )
    then
    <#if guideRuleInfo.whenStack?? && guideRuleInfo.whenStack?size != 0>
        <#list guideRuleInfo.thenStack! as thenStr>
        ${thenStr}
        </#list>
    </#if>
        if (!$insertMap.containsKey("${templateDrlInfo.preRuleName}_trigger_info")) {
            $insertMap.put("${templateDrlInfo.preRuleName}_trigger_info", new ArrayList<String>());
        }
        List<String> triggerInfoList = (ArrayList<String>) $insertMap.get("${templateDrlInfo.preRuleName}_trigger_info");
        triggerInfoList.add("${guideRuleInfo.ruleName}");

        $insertMap.put("${templateDrlInfo.preRuleName}_trigger_flag", true);
        update($insertMap);
end

<#list guideRuleInfo.drlInfoList! as drlInfo>
${drlInfo}
</#list>
</#list>

rule "${templateDrlInfo.preRuleName}"
salience 9999
lock-on-active true
    when
        $insertMap: Map()
    then
        if (!$insertMap.containsKey("trigger_info")) {
            $insertMap.put("trigger_info", new ArrayList<String>());
        }
        List<String> triggerInfoList = (ArrayList<String>) $insertMap.get("trigger_info");
        triggerInfoList.add("${templateDrlInfo.preRuleName}");
end
